package com.zFace.多线程轮流打印;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 用 ReentrantLock、三个 Condition 实现 三个线程轮流打印十次
 */
public class Demo4 {

	private static int index = 1;

	public static void main(String[] args) throws InterruptedException {
		final ReentrantLock lock = new ReentrantLock();
		final Condition condition1 = lock.newCondition();
		final Condition condition2 = lock.newCondition();
		final Condition condition3 = lock.newCondition();

		Thread t1 = new Thread(new Runnable() {
			public void run() {
				lock.lock();
				try {
					for (int i = 0; i < 10; i++) {
						while (index % 3 != 1) {
							condition1.await();
						}
						System.out.println("a");
						index++;
						condition2.signal();
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		});
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				lock.lock();
				try {
					for (int i = 0; i < 10; i++) {
						while (index % 3 != 2) {
							condition2.await();
						}
						System.out.println("b");
						index++;
						condition3.signal();
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		});
		Thread t3 = new Thread(new Runnable() {
			public void run() {
				lock.lock();
				try {
					for (int i = 0; i < 10; i++) {
						while (index % 3 != 0) {
							condition3.await();
						}
						System.out.println("c");
						index++;
						condition1.signal();
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		});
		t1.start();
		t2.start();
		t3.start();
		Thread.sleep(1000);
		System.out.println(index - 1);
	}
}
